package org.mayuanxiaonong.timservice;

import java.util.UUID;

import org.mayuanxiaonong.timservice.config.HostConfig;
import org.mayuanxiaonong.timservice.config.SystemConfig;
import org.mayuanxiaonong.timservice.pojo.Host;
import org.mayuanxiaonong.timservice.pojo.Presence;
import org.mayuanxiaonong.timservice.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ServerHandler extends SimpleChannelInboundHandler<String> {
	
	private static Logger log = LoggerFactory.getLogger(ServerHandler.class);
	private UserService userService = SystemConfig.getInstance().getBean(UserService.class);

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		JSONObject json = JSONObject.parseObject(msg);
		if(json.getBooleanValue("login")) {
			// 登陆请求
			int uid = json.getIntValue("uid");
			String pword = json.getString("pword");
			// 鉴权
			boolean ok = userService.login(uid, pword);
			// 返回响应信息
			JSONObject resp = new JSONObject();
			resp.put("login", true);
			if(ok) {
				Presence presence = new Presence();
				presence.setUid(uid);
				presence.setTime(System.currentTimeMillis());
				presence.setToken(UUID.randomUUID().toString());
				Host host = HostConfig.getInstance().hitHost(String.valueOf(uid));
				presence.setHost(host.getIp());
				presence.setPort(host.getPort());
				userService.savePresence(presence);
				
				resp.put("success", true);
				resp.put("uid", uid);
				resp.put("token", presence.getToken());
				resp.put("host", presence.getHost());
				resp.put("port", presence.getPort());
				resp.put("tms", System.currentTimeMillis());
			} else {
				resp.put("success", false);
				resp.put("msg", "");
			}
			ctx.writeAndFlush(resp.toString());
			ctx.close();
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		super.exceptionCaught(ctx, cause);
		log.error("发生异常", cause);
		ctx.close();
	}

}
